package com.hrc.springbootdemo.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author hrc
 */
@Aspect
@Component
@Slf4j
public class TestAop {

    @Pointcut("@annotation(com.hrc.springbootdemo.aop.AopDemo)")
    public void pointCut() {
    }

    /**
     * 拿到注解的值
     */
    @Around("pointCut()")
    public Object getValue(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法上的 AopDemo 注解
        AopDemo annotation = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(AopDemo.class);
        if (annotation != null) {
            // 获取注解的值
            String value = annotation.value();
            log.info("AopDemo 注解的值: {}" , value);
        }

        log.info("around begin");
        Object result = joinPoint.proceed();
        log.info("around end");
        return result;
    }


    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("around begin");
        Object result = joinPoint.proceed();
        System.out.println("around end");
        return result;
    }

    @Before("pointCut()")
    public void before() {
        System.out.println("before begin");
    }

    @After("pointCut()")
    public void after() {
        System.out.println("after begin");
    }

    @AfterThrowing("pointCut()")
    public void afterThrowing() {
        System.out.println("after throwing");
    }

    @AfterReturning("pointCut()")
    public void afterReturning() {
        System.out.println("after returning");
    }
}
